var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var tg3Util = require('./util/tg3Util.js');
var rpcFunc=require('../routes/rpcSrv/rpcFunc.js');
var superagent = require('superagent');

var ItbUserModel = require('../../common/mysql/mapping/ItbUserModel');
var TgDesignDocModel = require('../../common/mysql/mapping/TgDesignDocModel');
var TgDesignPageModel = require('../../common/mysql/mapping/TgDesignPageModel');
var TgUserDocModel = require('../../common/mysql/mapping/TgUserDocModel');
var TgUserPageModel = require('../../common/mysql/mapping/TgUserPageModel');
var TgUserPcModel = require('../../common/mysql/mapping/TgUserPcModel');
var TgTypeModel = require('../../common/mysql/mapping/TgTypeModel');
var OSSMgr = require('../../common/util/OSSMgr');
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');

var SJGNode = require('../sjg/common/tg/SJGNode');
var SJGTG = require('../sjg/common/tg/SJGTG');
var SJGNodeV3 = require('../sjg/common/tg3/SJGNodeV3');
var SJGTGV3 = require('../sjg/common/tg3/SJGTGV3');

var async = require( 'async'); // 同步控制

var moment = require('moment');  // 日期格式化

var BASE_IP = CONFIG.BASE_IP;



//------------------------------------------------------------------
/* 获取首页内容信息
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *        "hostSearch":"大家都在搜 双十一",
 *        "adInfo":{
 *          "url":"http://www.itbour.com",
 *          "thumb":"http://oss-image",
 *          "title":"一键生成女朋友"
 *        },
 *        "hotsProject":{
 *          "title":"热门专题",
 *          "list":[{"id":321,  "thumb":"http://oss-image", "title":"小清新风格",    "desc":"夏季清风",  "typeL":0}]
 *        },
 *        "hotsPPT":{
 *            "title":"热门幻灯片推荐",
 *            "list":[{"id":38599,"thumb":"http://oss-image"}]
 *        },
 *        "hotsPoster":{
 *            "title":"热门海报推荐",
 *            "list":[{"id":23432,"thumb":"http://oss-image"}]
 *        },
 *        "hotsMultiPage":{
 *            "title":"热门多页推荐",
 *            "list":[{"id":23432, "thumb":"http://oss-image"}]
 *        },
 *        "hotsBusinessCard":{
 *            "title":"热门名片推荐",
 *            "list":[{"id":23432, "thumb":"http://oss-image"}] // 商品信息
 *        },
 *        "hotsLeaflet":{
 *            "title":"热门传单推荐",
 *            "list":[{"id":23432, "thumb":"http://oss-image"}] // 商品信息
 *        },
 *        "poseterTypeM":[{"name":"最新","id":23}],
 *        "multiPageTypeM":[{"name":"最新","id":23}]
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getMainPage
 * */
function getMainPage(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '1');

    async.series([
            function(callback){
                // type:分类: 1单页, 2多页, 3ppt，可以为null
                tg3Util.get_hotsSearch(null, function(error,data){ callback(error,data)});//*** results[0]
            },
            function(callback){
                tg3Util.get_adInfo(function(error,data){ callback(error,data)});//*** results[1]
            },
            function(callback){
                tg3Util.get_hotsProject(function(error,data){ callback(error,data)});//*** results[2]
            },
            function(callback){
                tg3Util.get_hotsPPT(function(error,data){ callback(error,data)});//*** results[3]
            },
            function(callback){
                tg3Util.get_hotsPoster(function(error,data){ callback(error,data)});//*** results[4]
            },
            function(callback){
                tg3Util.get_hotsMultiPage(function(error,data){ callback(error,data)});//*** results[5]
            },
            function(callback){
                tg3Util.get_hotsBusinessCard(function(error,data){ callback(error,data)});//*** results[6]
            },
            function(callback){
                tg3Util.get_hotsLeaflet(function(error,data){ callback(error,data)});//*** results[7]
            },
            function(callback){
                tg3Util.get_poseterTypeM(function(error,data){ callback(error,data)});//*** results[8]
            },
            function(callback){
                tg3Util.get_multiPageTypeM(function(error,data){ callback(error,data)});//*** results[9]
            },
        ],

        function(err, results){
            if(err){
                console.log(err);
                return tg3Util.ret_func_json(0,'error',{},res);
            }

            var data = {
                "hotsSearch":       results[0].length>0?results[0][0]:'',
                "adInfo":           results[1],
                "hotsProject":      {title:"热门专题", list:results[2]},
                "hotsPPT":          {title:"热门幻灯片推荐", list:results[3]},
                "hotsPoster":       {title:"热门海报推荐", list:results[4]},
                "hotsMultiPage":    {title:"热门多页推荐", list:results[5]},
                "hotsBusinessCard": {title:"热门名片推荐", list:results[6]},
                "hotsLeaflet":      {title:"热门传单推荐", list:results[7]},
                "poseterTypeM":     results[8],
                "multiPageTypeM":   results[9],
                "printAlert" :      ""
            };
            return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        });
}
router.get('/getMainPage', getMainPage);
router.post('/getMainPage', getMainPage);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取热门设计列表
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数: projectId: 专题唯一标识 id
 * 参数: pageNum: 请求页
 * 参数: pageSize: 请求页大小
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *        "list":[{ "type":1, "id":123, "thumb":"http://oss-image", "name":"xxx" }] // 印品时id为商品id
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getSpecialTopicItems?projectId=3
 * */
function getSpecialTopicItems(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var projectId = Number(req.body.projectId || req.query.projectId || '0');
    var pageNum = Number(req.body.pageNum || req.query.pageNum || '0');
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '12');

    tg3Util.getSpecialTopicItems(projectId, pageNum, pageSize, function(error, data){
        if(error){
            console.log(error);
            return tg3Util.ret_func_json(0,'error',{},res);
        }
        tg3Util.getSpecialTopicColumn(projectId, function(error, column){
            if(error){
                console.log(error);
                return tg3Util.ret_func_json(0,'error',{},res);
            }

            return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, {"list":data, "column":column}, res);
        });
    });

}
router.get('/getSpecialTopicItems', getSpecialTopicItems);
router.post('/getSpecialTopicItems', getSpecialTopicItems);

//------------------------------------------------------------------

/**  根据大分类中分类获取对应列表 
 * 方式 get/post 
 * 参数 device : 0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios 
 * 参数 uuid   : 设备唯一标识 
 * 参数 userId[可选] : 用户唯一标识 
 * 参数 typeL  : 大分类标记 0 未分类(不可出现)   1 海报  2 多页  3 ppt 
 * 参数 typeM  : 对应大分类下的二级分类 
 * 参数 pageNum : 页码, 从0开始, 默认为0 
 * 参数 pageSize: [0或空:忽略pageNum获取全部记录] 
 * 参数 withTotalPage［可选］:1表示需要返回总页数 (对应返回字段: totalPageCount) 
 * {"success":1, 
 *  "msg":"成功", 
 *  "data":{ 
 *      "totalPageCount" : 9 
 *      "list":[ 
 *          {"id":768,"thumb":"http://oss-image-xxxx.jpg"}, 
 *          {"id":768,"thumb":"http://oss-image-xxxx.jpg"} 
 *        ]
 *      }
 * } 
 * */

function getEquivalentTypeList(req, res, next) {
    // get parameters
    var device = req.query.device || req.body.device;
    var uuid = req.query.uuid || req.body.uuid;
    var userId = req.userId || req.body.userId; 
    var typeL = Number(req.query.typeL || req.body.typeL || 0); 
    var typeM = Number(req.query.typeM || req.body.typeM || 0); 
    var pageNum = Number(req.query.pageNum || req.body.pageNum || 0); 
    var pageSize = Number(req.query.pageSize || req.body.pageSize || 0); 
    var withTotalPage = Number(req.query.withTotalPage || req.body.withTotalPage || 0); 
    var typeS = -1; // 标识小分类为不限, 获取中分类下所有内容
    // 返回数据
    function ret_func(success, msg, data){ 
        var obj = { 
            success: success, 
            msg: msg, 
            data: data 
        }; 
        res.set('Content-Type', 'application/json'); 
        res.json(obj); 
    }
    // check parameters
    if(typeof typeL == 'undefined' || isNaN(typeL) || typeL == null || typeL == 0) {
        return ret_func(0, "大分类未指定"); 
    } 
    if (typeof typeM=='undefined' || isNaN(typeM) || typeM==null) { 
        return ret_func(0,"中分类未指定"); 
    }
    // 暂时只支持海报/多页
    if(typeL != 1 && typeL != 2) {
        return ret_func(0, "大分类无效"); 
    }
    // 分页: 跳过条数 
    var skipCnt = pageNum * pageSize;
    // 海报/多页
    if(typeL == 1 || typeL == 2) {
        // 请求数据处理
        function proc_func(items, totalPageCount) {
            var list = []; 
            for (var i in items) { 
                var item = items[i]; 
                var itemData = { 
                    "id": item.design_id, 
                    "thumb": item.thumb, 
                } 
                list.push(itemData); 
            }
            // 创建返回 
            var retData = {
                "list" : list, 
            } 
            // 如果需要多页信息 
            if(withTotalPage>=0){ 
                retData.totalPageCount = totalPageCount; 
            } 
            return ret_func(1,CODE.OPERATION_SUCCESS,retData);
        }

        // 查询数据 
        var entity = new TgDesignDocModel({ 
            publish: 1, 
        });
        // 从数据库中查询数据
        entity.getDocAndPagesInfoByType(function(err, items){ 
            if (err){ 
                console.log('tg.js [getDesignList] getInfo Err: '+err);
                return ret_func(0,CODE.OPERATION_FAILED); 
            }
            // 如果需要请求所有页数, 再次查询
            if(withTotalPage>0){
                entity.getDocAndPagesInfoByTypeCnt(function(err2, count){ 
                    if (err2){ 
                        console.log('tg.js [getDesignList] getInfo Cnt Err: '+err2);
                         return ret_func(0,CODE.OPERATION_FAILED); 
                    } 
                    var pgCnt = 1; 
                    if(pageSize>0) { 
                        pgCnt = Math.floor((count-1)/pageSize)+1; 
                    } 
                    proc_func(items, pgCnt);
                 }, typeM, typeS,typeL);
            } else { 
                proc_func(items); 
            }
        }, typeM, typeS,typeL, skipCnt, pageSize);
    }

}
 router.get('/getEquivalentTypeList', getEquivalentTypeList); 
router.post('/getEquivalentTypeList', getEquivalentTypeList);

//------------------------------------------------------------------
/* 获取获取热门关键词
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数: typeL:  搜索分类,  0 未分类   1 海报  2 多页  3 ppt
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *        "hotsSearch":["小清新","简约"]
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getHotsSearch?typeL=0
 * */
function getHotsSearch(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '0');


    tg3Util.get_hotsSearch(typeL, function(error, data){
        if(error){
            console.log(error);
            return tg3Util.ret_func_json(0,'error',{},res);
        }

        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, {"hotsSearch":data}, res);
    });

}
router.get('/getHotsSearch', getHotsSearch);
router.post('/getHotsSearch', getHotsSearch);



//------------------------------------------------------------------
/* 根据关键词搜索对应模板
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数 keyword:  关键词(去特殊字符, 以 空格分割, 以 半角 , 拼接)
 * 参数 typeL:  搜索分类,  0 未分类   1 海报  2 多页  3 ppt  4 印品
 * 参数 pageNum: 搜索结果对应页
 * 参数 pageSize: 搜索结果请求页大小
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *        "result":[{
 *              "thumb":"http://xxx.jpg", // 如typeL为4则id为印品商品图片,否则为模版图片
 *              "id":788, // 如typeL为4则id为印品商品id,否则为模版id
 *              "typeL":1,
 *              "desc":"幻灯片",
 *              "author":"by乌头马角工作室"
 *          }]
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/search?keyword=奇怪,严肃&pageSize=3&pageNum=0&typeL=1
 * */
function search(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var keyword = req.body.keyword || req.query.keyword || '';
    var typeL = Number(req.body.typeL || req.query.typeL || '0');
    var pageNum = Number(req.body.pageNum || req.query.pageNum || '0');
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '12');

    if(keyword.length==0){
        return tg3Util.ret_func_json(0,CODE.SERACH_KEYWORD_EMPTY,{},res);
    }
    if(keyword.length>10){
        return tg3Util.ret_func_json(0,CODE.SERACH_KEYWORD_TOO_LONG,{},res);
    }


    tg3Util.get_search(keyword,typeL, pageNum, pageSize, function (error, data) {
        if (error) {
            console.log('tg3.js search error: '+error);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, {"result":data}, res);
    });
}
router.get('/search', search);
router.post('/search', search);


//------------------------------------------------------------------
/* 根据顶级分类获取对应标签
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数 typeL:  1 海报  2 多页
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *        "tags":[{
 *          "id":788,
 *          "name":"邀请函",
 *          "sub":[{
 *              "id":788,
 *              "name":"展会",
 *          }]
 *        }]
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getTagByTypeL?typeL=1
 * */
function getTagByTypeL(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '0');



    tg3Util.getTagByTypeL(typeL,function (error, data) {
        if (error) {
            console.log('tg3.js search error: '+error);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, {"tags":data}, res);
    });
}
router.get('/getTagByTypeL', getTagByTypeL);
router.post('/getTagByTypeL', getTagByTypeL);


//------------------------------------------------------------------
/* 根据指定标签数组 和 对应条目信息, 获取指定模板
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数 typeL:  1 海报  2 多页
 * 参数 tags:  标签页面选择的标签对应的标签 id 数组，例如：[12]
 * 参数 optionalIds: 条目选择界面的所有选中的 可选条目对应节点的 id 数组, 例如：[45, 78, 99]
 * 参数 tgId:  条目选择获取的 tgId
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *      "productId":0,
 *      "designId":321,
 *      "coreStructure":{"version":3,"name":"会议邀请函","root":{}}
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getDesignByItem?tgId=214&optionalIds=[]
 * */
function getDesignByItem(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '0');
    var tags = JSON.parse(req.body.tags || req.query.tags || '[]');
    var optionalIds = JSON.parse(req.body.optionalIds || req.query.optionalIds || '[]');
    var tgId = Number(req.body.tgId || req.query.tgId || '0');

    if(tgId<=0){
        return tg3Util.ret_func_json(0,CODE.DOC_ID_INVAILD,{},res);
    }

    // 获取题纲的数据
    tg3Util.getDesignByItem(optionalIds, tgId, 0, function(error, data){
        if (error) {
            console.log('tg3.js getDesignByItem error: '+error);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!data){
            // 返回失败
            return tg3Util.ret_func_json(0,CODE.CANNOT_FIND_DESIGN,{},res);
        }
        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, data, res);

    });
}

router.get('/getDesignByItem', getDesignByItem);
router.post('/getDesignByItem', getDesignByItem);


//------------------------------------------------------------------
/* 根据指定标签数组获取对应条目数据
 * 方式:GET/POST
 * 参数 device:0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数 uuid: 设备标识
 * 参数[可选]: userId:用户唯一标识
 * 参数 typeL:  1 海报  2 多页
 * 参数 tags:  标签页面选择的标签对应的标签 id 数组，例如：[12]
 * 返回:
 *{
 *    "success":0,
 *    "msg":"成功",
 *    "data":{
 *      "tgId":758,
 *      "tree":{"version":3,"name":"会议邀请函","root":{}}
 *    }
 *}
 * 测试地址：http://localhost:3000/tg3/getItemByTag?typeL=1&tags=[802]
 * */
function getItemByTag(req, res, next) {
    var THIS = this;
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '0');
    var tags = JSON.parse(req.body.tags || req.query.tags || '[]');

    if(tags.length!=1){
        return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
    }

    var typeS = tags[0];// 三级分类
    tg3Util.getItemByTypeS(typeS,function (error, data) {
        if (error) {
            console.log('tg3.js getItemByTag error: '+error);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getItemByTag', getItemByTag);
router.post('/getItemByTag', getItemByTag);

//------------------------------------------------------------------
/*
 接口名称:getFineTuneOfUserDoc
 参数：device
 参数：uuid
 参数：docId
 返回结果：
 {
     "success":1,
     "msg":"成功",
     "data":{
         "id":1,
         "pageWidth":720,
         "pageHeight":1280,
         "bleed":36,
         "pageCount":3,
         "textObjects":"[{\"ct\":607,\"id\":1}]",// 所有页root对象只保留TextExtObj(且只保留fz\te\style\color\id\pos几个属性)
         "fonts": [{"font" : "平方中","thumb": "http://itbour-user.oss-cn-hangzhou.aliyuncs.com/font/pingfangzhong.png"}], // [v5_1新增]
 }
 }
 */
function getFineTuneOfUserDoc(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var userId = Number(req.body.userId || req.query.userId || '0');
    var docId = Number(req.body.docId || req.query.docId || '0');
    if(userId <= 0) {
        return tg3Util.ret_func_json(0,CODE.USER_ID_INVAILD,{},res);
    }
    if(docId <= 0) {
        return tg3Util.ret_func_json(0,CODE.DOC_ID_INVAILD,{},res);
    }

    tg3Util.getFineTuneOfUserDoc(docId, userId, function(err, ret){
        if(err){
            console.log('tg3.js getFineTuneOfUserDoc error: '+err);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, ret, res);
    });



}
router.get('/getFineTuneOfUserDoc', getFineTuneOfUserDoc);
router.post('/getFineTuneOfUserDoc', getFineTuneOfUserDoc);


////------------------------------------------------------------------
///*
// 接口名称:saveTextObjects
// 参数：userId
// 参数：docId
// 参数：textObjects：string的数组类型，所有页文字属性列表的JSON，结构类似于getFineTuneOfUserDoc返回的textObjects
// 返回：
// {
//    "success":1,
//    "msg":"成功"
// }
// */
function saveTextObjects(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var THIS = this;

    var userId = Number(req.body.userId || req.query.userId || '0');
    var docId = Number(req.body.docId || req.query.docId || '0');
    var ftData = req.body.textObjects || req.query.textObjects || '';

    if(userId <= 0) {
        return tg3Util.ret_func_json(0,CODE.USER_ID_INVAILD,{},res);
    }
    if(docId <= 0) {
        return tg3Util.ret_func_json(0,CODE.DOC_ID_INVAILD,{},res);
    }

    tg3Util.updFineTuneOfUserDoc(docId, userId, 1, ftData, function(err, ret){
        if(err){
            console.log('tg3.js saveTextObjects error: '+err);
            return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS, {}, res);
    });

}
router.get('/saveTextObjects', saveTextObjects);
router.post('/saveTextObjects', saveTextObjects);
//

//------------------------------------------------------------------

module.exports = router;
